<script lang="ts" setup>
import { ref } from 'vue'

import { useRequest } from 'vue-request'
import AdvancedTable from '@/components/sofastui/AdvancedTable/AdvancedTable.vue'
import AdvancedForm from '@/components/sofastui/AdvancedForm/AdvancedForm.vue'
import DatatablefieldPage from './components/datatablefield/DatatablefieldPage.vue'

import { fields, config, formRules } from './constant'
import { DatasourceService } from '@/services/api/dev/datasource.service'

const advancedFormRef = ref()
const advancedTableRef = ref()

const visible = ref(false)
const selectRow = ref(undefined)

const searchFormData = ref<{
  dataSourceId?: number
}>({})

const { data, loading } = useRequest(DatasourceService.list, {
  defaultParams: [{}],
  onSuccess(data) {
    if (data?.length) searchFormData.value.dataSourceId = data[0].id
  },
})

// 创建
const handelAdd = () => {
  advancedFormRef.value?.show('add', {})
}

// 行展开
const handelRowExpand = (data: { [key: string]: unknown }) => {
  advancedFormRef.value?.show('update', data)
}

// 刷新表格数据
const refreshTableData = () => {
  advancedTableRef.value!.refresh()
}

// 查看字段
const handelShow = (row) => {
  console.log(row)
  selectRow.value = row
  visible.value = true
}
</script>

<template>
  <LTable>
    <template #header>
      <div>
        <el-select v-model="searchFormData.dataSourceId" class="min-w-56">
          <el-option v-for="item in data" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </div>
    </template>
    <template v-if="!loading">
      <AdvancedTable
        ref="advancedTableRef"
        :query="searchFormData"
        :fields="fields"
        :config="config"
        @add="handelAdd"
        @rowExpand="handelRowExpand"
      >
        <template #table-row-operate="scope">
          <el-button class="!p-2" type="primary" @click="handelShow(scope.row)">
            <el-icon>
              <List />
            </el-icon>
          </el-button>
        </template>
      </AdvancedTable>
    </template>
  </LTable>
  <!-- 修改表单 -->
  <AdvancedForm
    ref="advancedFormRef"
    :config="config"
    :rule="[
      {
        type: 'hidden',
        field: 'dataSourceId',
        value: searchFormData.dataSourceId,
      },
      ...formRules,
    ]"
    @success="refreshTableData"
  />
  <el-dialog
    title="字段配置"
    v-model="visible"
    width="1200px"
    :close-on-click-modal="false"
    :append-to-body="true"
  >
    <DatatablefieldPage :selectRow="selectRow" />
  </el-dialog>
</template>
